﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
namespace IEC
{
    //tool config
    public class IECConfigSavedDatas
    {
        public LinkedList<SavedModList> modLists = new LinkedList<SavedModList>();
        public bool ReadFromSteam = true;
        public string AlternateGamePath = null;
    }
    public class IECConfig
    {
        string config_path = null;
        public IECConfig()
        {
            var document = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var gameFolder = System.IO.Path.Combine(document, "My Games", "IsaacExternalConfigure");
            var dir = new System.IO.DirectoryInfo(gameFolder);
            if (!dir.Exists)
            {
                dir.Create();
            }
            config_path = System.IO.Path.Combine(gameFolder, "config.json");
            LoadAll();
        }
        public bool ReadFromSteam { get => savedDatas.ReadFromSteam; set => savedDatas.ReadFromSteam = value; }
        public string GamePath { get => savedDatas.AlternateGamePath; set => savedDatas.AlternateGamePath = value; }
        IECConfigSavedDatas savedDatas = new IECConfigSavedDatas();

        public LinkedList<SavedModList> Mods { get { return savedDatas.modLists; } }

        public void SnapshootNewList(ModList mods)
        {
            savedDatas.modLists.AddLast(new SavedModList() { name = System.DateTime.Now.ToString("g"), list = new ModList(mods) });
        }

        public void SnapshotOldList(ModList mods, SavedModList toList)
        {
            toList.list.List.Clear();
            foreach(var froms in mods.List)
            {
                toList.list.List.AddLast(new ModListItem(froms));
            }
        }

        public void SaveAll()
        {
            string json = JsonConvert.SerializeObject(savedDatas);
            try
            {
                System.IO.File.WriteAllText(config_path, json);
                MessageBox.Show("配置保存成功");
            }catch(Exception e)
            {
                MessageBox.Show(e.Message, "配置保存失败");
            }

        }

        public bool LoadAll()
        {
            try
            {
                string json = System.IO.File.ReadAllText(config_path);
                savedDatas = JsonConvert.DeserializeObject<IECConfigSavedDatas>(json);
                return true;
            }catch(Exception e)
            {
                return false;
            }
        }
    }

    public class SavedModList
    {
        public string name;
        public ModList list;
    }
}
